package org.example.utils;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;


@Slf4j
@Component
public class I18nUtil {

    private static MessageSource messageSource;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 获取code对应的转义信息
     */
    public static String getMessage(String code) {
        String data = "";
        boolean isGet = true;
        try {
            data = messageSource.getMessage(code, null, "", LocaleContextHolder.getLocale());
        } catch (Exception e) {
            //log.debug("I18nUtil get key:{} error", code);
            isGet = false;
        }

        if (!isGet) {
            // 未查到再查一次中文
            try {
                data = messageSource.getMessage(code, null, "", Locale.SIMPLIFIED_CHINESE);
            } catch (Exception e) {
                //log.debug("I18nUtil get key:{} error", code);
                return code;
            }
        }

        return data;
    }

    /**
     * 获取code对应的转义信息
     * 匹配不到返回默认值
     */
    public static String getMessage(String code, String defaultMessage) {
        String data = defaultMessage;
        boolean isGet = true;
        try {
            data = messageSource.getMessage(code, null, defaultMessage, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            //log.debug("I18nUtil get key:{} error", code);
            isGet = false;
        }

        if (!isGet) {
            // 未查到再查一次中文
            try {
                data = messageSource.getMessage(code, null, defaultMessage, Locale.SIMPLIFIED_CHINESE);
            } catch (Exception e) {
                //log.debug("I18nUtil get key:{} error, e:", code, e);
                return defaultMessage;
            }
        }

        return data;
    }

    /**
     * 设置缺省语言为简体中文
     */
    public static void setDefaultSimplified() {
        // 设置缺省语言为中文
        LocaleContextHolder.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
    }

    /**
     * 设置语言
     */
    public static void setLocale(String language, String country) {
        LocaleContextHolder.setLocale(new Locale(language, country));
    }

    @PostConstruct
    public void init() {
        I18nUtil.messageSource = applicationContext.getBean(MessageSource.class);
    }
}
